package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import naga.x.util.NumberUtils;
import naga.x.util.StringUtils;

public class LongArrayTypeHandler extends BaseTypeHandler<long[]> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, long[] vals, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, vals != null ? serialize(vals) : null);
	}

	@Override
	public long[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return deserialze(rs.getString(columnName));
	}

	@Override
	public long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return deserialze(rs.getString(columnIndex));
	}

	@Override
	public long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return deserialze(cs.getString(columnIndex));
	}
	
	private static long[] deserialze(String text) {
		if (StringUtils.isEmpty(text)) {
			return null;
		}
		String[] strs = StringUtils.split(text, ",");
		long[] vals = new long[strs.length];
		for (int i = 0; i < strs.length; i++) {
			vals[i] = NumberUtils.parseLong(StringUtils.trim(strs[i]));
		}
		return vals;
	}
	
	private static String serialize(long[] vals) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0, len = vals.length; i < len; i++) {
			if (i != 0) {
				builder.append(',');
			}
			builder.append(vals[i]);
		}
		return builder.toString();
	}

}
